package com.kgc.crowd.distributioncrowdwebui.controller;

import com.kgc.crowd.distributioncrowdcommon.api.MemberManagerRemoteService;
import com.kgc.crowd.distributioncrowdcommon.api.ProjectManagerRemoteService;
import com.kgc.crowd.distributioncrowdcommon.pojo.*;
import com.kgc.crowd.distributioncrowdcommon.util.CrowdConstant;
import com.kgc.crowd.distributioncrowdcommon.util.CrowdUtils;
import com.kgc.crowd.distributioncrowdcommon.util.UploadUtil;
import com.kgc.crowd.distributioncrowdcommon.vo.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/project/manager")
public class ProjectController {
    @Value("${endpoint}")
    private String endpoint;
    @Value("${accessKeyId}")
    private String accessKeyId;
    @Value("${accessKeySecret}")
    private String accessKeySecret;
    @Value("${headerPictureFolderName}")
    private String headerPictureFolderName;
    @Value(("${detailPictureFolderName}"))
    private String detailPictureFolderName;
    @Value("${bucketName}")
    private String bucketName;
    @Value("${domain}")
    private String domain;
    @Value("${returnFloderName}")
    private String returnFloderName;

    @Resource
    ProjectManagerRemoteService projectManagerRemoteService;

    @Resource
    MemberManagerRemoteService memberManagerRemoteService;

    @RequestMapping("/start")
    public String start() {
        return "start";
    }

    @RequestMapping("/agree/protocol")
    public String agreeProtocol(HttpSession session, Model model) {
        //获取登录状态
        Object obj = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if (obj == null) {
            return "redirect:/to/login.html";
        }
        MemberSignSuccessVO memberSignVO = (MemberSignSuccessVO) obj;
        String token = memberSignVO.getToken();
        //加载分类信息
        ResultEntity<List<TypePO>> listResultEntity = projectManagerRemoteService.selectAllType();
        System.out.println(listResultEntity.getData());
        model.addAttribute(CrowdConstant.ATTR_NAME_TYPEPO_LIST, listResultEntity.getData());
        //加载标签信息
        ResultEntity<List<TagVO>> allTag = projectManagerRemoteService.selectAllTag();
        model.addAttribute(CrowdConstant.ATTR_NAME_TAG_LIST, allTag.getData());
        //回显发起人信息
        ResultEntity<MemberLaunchInfoPO> memberLaunchInfoPOResultEntity = memberManagerRemoteService.retrieveMemberLaunchInfoPOByMemberToken(token);
        System.out.println(memberLaunchInfoPOResultEntity.getData());
        model.addAttribute(CrowdConstant.ATTR_NAME_MEMBERLAUNCHINFO, memberLaunchInfoPOResultEntity.getData());
        //初始化ProjectVO
        ResultEntity<ProjectVO> resultEntity = projectManagerRemoteService.initCreation(token);
        if (ResultEntity.FAILED.equals(resultEntity.getResult())) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, resultEntity.getMessage());
            return "redirect:/project/manager/start";
        }
        //把ProjectVO存入Session
        ProjectVO projectVO = resultEntity.getData();
        session.setAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT, projectVO);
        return "start-step-1";
    }

    @RequestMapping("/upload/head/picture")
    @ResponseBody
    public ResultEntity<String> uploadHeaderPicture(MultipartFile headerPicture, HttpSession session) throws IOException {
        Object obj = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if (obj == null) {
            return ResultEntity.failed(CrowdConstant.MESSAGE_ACCESS_DENIED);
        }
        MemberSignSuccessVO memberSignSuccessVO = (MemberSignSuccessVO) obj;
        String memberSignToken = memberSignSuccessVO.getToken();
        Object obj2 = session.getAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT);
        if (obj2 == null) {
            return ResultEntity.failed(CrowdConstant.ATTR_NAME_NO_INITED_PROJECT);
        }
        ProjectVO projectVO = (ProjectVO) obj2;
        String projectTempToken = projectVO.getProjectTempToken();
        //验证是否选择文件
        if (headerPicture == null) {
            return ResultEntity.failed(CrowdConstant.MESSAGE_NO_FILE);
        }
        //获取旧的文件名，生成新的文件名
        String originalFilename = headerPicture.getOriginalFilename();
        String fileName = UploadUtil.generaterFileName(originalFilename);
        //把文件对象转换成文件流
        InputStream inputStream = headerPicture.getInputStream();
        //文件上传
        UploadUtil.uploadSingleFile(endpoint, accessKeyId, accessKeySecret, fileName, headerPictureFolderName, bucketName, inputStream);
        String headerPicturePath = domain + "/" + headerPictureFolderName + "/" + fileName;
        projectManagerRemoteService.saveHeadPicturePath(memberSignToken, projectTempToken, headerPicturePath);
        return ResultEntity.successNoData();
    }

    @ResponseBody
    @RequestMapping("/upload/detail/picture")
    public ResultEntity<String> uploadDetailPicture(
            HttpSession session,
            @RequestParam("detailPicture") List<MultipartFile> detailPictureList
    ) throws IOException {
        // 登录检查
        MemberSignSuccessVO signVO = (MemberSignSuccessVO) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if (signVO == null) {
            return ResultEntity.failed(CrowdConstant.MESSAGE_ACCESS_DENIED);
        }
        // 遍历用户上传的文件
        if (!CrowdUtils.collectionEffectiveCheck(detailPictureList)) {
            return ResultEntity.failed(CrowdConstant.MESSAGE_NO_FILE);
        }
        List<String> detailPicturePathList = new ArrayList<>();
        for (MultipartFile detailPicture : detailPictureList) {
            boolean empty = detailPicture.isEmpty();
            if (empty) {
                continue;
            }
            InputStream inputStream = detailPicture.getInputStream();
            String originalFileName = detailPicture.getOriginalFilename();
            String fileName = UploadUtil.generaterFileName(originalFileName);
            UploadUtil.uploadSingleFile(endpoint, accessKeyId, accessKeySecret, fileName, detailPictureFolderName, bucketName, inputStream);
            String detailPicturePath = domain + "/" + detailPictureFolderName + "/" + fileName;
            detailPicturePathList.add(detailPicturePath);
        }
        // 获取保存头图所需要的相关信息
        String memberSignToken = signVO.getToken();
        ProjectVO projectVO = (ProjectVO) session.getAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT);
        String projectTempToken = projectVO.getProjectTempToken();
        return projectManagerRemoteService.saveDetailPicturePathList(memberSignToken, projectTempToken, detailPicturePathList);

    }


    @ResponseBody
    @RequestMapping("/save/project/information")
    public ResultEntity<String> saveProjectInformation(ProjectVO projectVO, HttpSession session) {
        MemberSignSuccessVO memberSignSuccessVO = (MemberSignSuccessVO) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if (memberSignSuccessVO == null) {
            return ResultEntity.failed(CrowdConstant.MESSAGE_ACCESS_DENIED);
        }
        String token = memberSignSuccessVO.getToken();
        projectVO.setMemberSignToken(token);
        ProjectVO projectVO1 = (ProjectVO) session.getAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT);
        if (projectVO1 == null) {
            return ResultEntity.failed(CrowdConstant.ATTR_NAME_NO_INITED_PROJECT);
        }
        projectVO.setProjectTempToken(projectVO1.getProjectTempToken());
        ResultEntity<String> stringResultEntity = projectManagerRemoteService.saveProjectInformation(projectVO);
        return stringResultEntity;
    }

    @RequestMapping("/project/manager/to/project/return")
    public String toProjectReturn() {
        return "start-step-2";
    }

    @RequestMapping("/save/return/vo")
    public String saveReturenVo(ReturnVO returnVO, HttpSession session, @RequestParam("describPic") MultipartFile describPic, Model model) throws IOException {
        MemberSignSuccessVO memberSignSuccessVO = (MemberSignSuccessVO) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if (memberSignSuccessVO == null) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_ACCESS_DENIED);
            return "login";
        }
        String token = memberSignSuccessVO.getToken();
        Object obj2 = session.getAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT);
        if (obj2 == null) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, "请同意协议");
            return "start";
        }
        ProjectVO projectVO = (ProjectVO) obj2;
        String projectTempToken = projectVO.getProjectTempToken();
        if (describPic == null) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_NO_FILE);
            return "start-step-2";
        }
        String originalFilename = describPic.getOriginalFilename();
        String fileName = UploadUtil.generaterFileName(originalFilename);
        InputStream inputStream = describPic.getInputStream();
        UploadUtil.uploadSingleFile(endpoint, accessKeyId, accessKeySecret, fileName, returnFloderName, bucketName, inputStream);
        returnVO.setDescribPicPath(domain+"/"+returnFloderName+"/"+fileName);
        returnVO.setMemberSignToken(token);
        returnVO.setProjectTempToken(projectTempToken);
        ResultEntity<String> resultEntity = projectManagerRemoteService.saveReturnVO(returnVO);
        if (resultEntity.getResult().equals(ResultEntity.FAILED)) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, resultEntity.getMessage());
            return "start-step-2";
        }
        return "start-step-3";
    }

    @RequestMapping("/save/member/confim/info/vo")
    public String saveMemberConfirmInfoVo(MemberConfirmInfoVO confirmInfoVO,HttpSession session,Model model){
        MemberSignSuccessVO memberSignSuccessVO = (MemberSignSuccessVO) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if (memberSignSuccessVO == null) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_ACCESS_DENIED);
            return "login";
        }
        String token = memberSignSuccessVO.getToken();
        Object obj2 = session.getAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT);
        if (obj2 == null) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, "请同意协议");
            return "start";
        }
        ProjectVO projectVO = (ProjectVO) obj2;
        String projectTempToken = projectVO.getProjectTempToken();
      confirmInfoVO.setMemberSignToken(token);
      confirmInfoVO.setProjectTempToken(projectTempToken);
        ResultEntity<String> resultEntity = projectManagerRemoteService.saveMemberConfirmInfoVO(confirmInfoVO);
        if (resultEntity.getResult().equals(ResultEntity.FAILED)) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, resultEntity.getMessage());
            return "start-step-3";
        }

        ResultEntity<String> project = projectManagerRemoteService.saveWholeProject(token, projectTempToken);
        if (project.getResult().equals(ResultEntity.FAILED)) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, resultEntity.getMessage());
            return "start-step-3";
        }
        return "start-step-4";
    }
    @RequestMapping("/project")
    public String project(){

        return "project";
    }

    @RequestMapping("/pay-step-1")
    public String payStep1(){
        return "pay-step-1";
    }

    @RequestMapping("/pay-step-2")
    public String payStep2(){
        return "pay-step-2";
    }


    @ResponseBody
    @RequestMapping("/selectType")
    public ResultEntity<List<TypePO>>  selectType(){
        ResultEntity<List<TypePO>> resultEntity = projectManagerRemoteService.selectType();
        return resultEntity;
    }

    @RequestMapping("/select/project/itempic")
    @ResponseBody
    public ResultEntity<ProjectPO> selectPorjectItemPid(Integer id){
        return projectManagerRemoteService.selectPorjectItemPid(id);
    }
    @ResponseBody
    @RequestMapping("/select/project/member")
    public ResultEntity<List<ProjectPO>> selectProjectByMemberId(@RequestParam(value="id", defaultValue="0",required = false) Integer id){
        return  projectManagerRemoteService.selectProjectByMemberId(id);
    }
    @ResponseBody
    @RequestMapping("/select/project/advertisement")
    public ResultEntity<List<ProjectPO>> selectProjectAndAdvertisement(@RequestParam(value="id", defaultValue="0",required = false) Integer id){
        return  projectManagerRemoteService.selectProjectAndAdvertisement(id);
    }
    @ResponseBody
    @RequestMapping("/select/project/order")
    public ResultEntity<List<Order>> selectOrderAndProject(@RequestParam(value="id", defaultValue="0",required = false) Integer id){
        return  projectManagerRemoteService.selectOrderAndProject(id);
    }
@ResponseBody
    @RequestMapping("/select/project/return")
    public ResultEntity<ProjectPO> selectProjectAndReturn(@RequestParam(value="id", defaultValue="0",required = false) Integer id){
        return projectManagerRemoteService.selectProjectAndReturn(id);
    }
}
